package com.wh.blockquene;

/**
 * 
 *  Class Name: TestWaitAndNotify.java
 *  @author wanghao  DateTime 2016年7月26日 上午11:45:05 
 *  @company hongbo
 *  @email 1228675455@qq.com
 *  Description: 当多个线程进行wait的时候，notify唤醒线程会随机选取一个,notifyAll会唤醒所有的线程
 */
public class TestWaitAndNotify5 {

	public static void main(String[] args) {
		
		final StudentDao dao = new StudentDao();
		Thread t1 = new Thread() {

			@Override
			public void run() {
				dao.addStudent();
			}
			
		};
		
		Thread t2 = new Thread() {

			@Override
			public void run() {
				dao.addStudent1();
			}
			
		};
		Thread t3 = new Thread() {

			@Override
			public void run() {
				dao.deleteStudent();
			}
			
		};
		t1.start();
		t2.start();
		try {
			Thread.currentThread().sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t3.start();
	}
	
	static class StudentDao {
		
		public void addStudent() {
			System.out.println("addStudent开始运行");
			synchronized(this) {
				System.out.println("增加开始");
				try {
					this.wait();
					System.out.println("addStudent被唤醒");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("增加结束");
			}
		}
		
		public synchronized void addStudent1() {
			System.out.println("addStudent1开始运行");
			System.out.println("增加开始");
			try {
				this.wait();
				System.out.println("addStudent1被唤醒");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("增加结束");
		}
		
		public synchronized void deleteStudent() {
				System.out.println("删除开始");
				try {
					Thread.sleep(3000);
					this.notifyAll();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("删除结束");
		}
	}
	
}
